package cn.jdy.audit.admin;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.audit.entity.ForumRecord;
import cn.jdy.audit.service.ForumRecordService;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.platform.service.ConfService;

/**
 * 数据分析论坛记录数据
 * 
 * @author yym
 * @since 110116
 */
@Controller
@RequestMapping("/forumRecord")
public class ForumRecordCtrl extends BaseCtrl {

	@Autowired
	private ForumRecordService forumRecordService;
	@Autowired
	private ConfService confService;
	// 默认列表路径
	private static String viewName = "redirect:/forumRecord/list?s=";

	/**
	 * 初始化
	 * 
	 * @param fr
	 * @param fromDate
	 * @param toDate
	 * @param s
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView list(ForumRecord fr, String fromDate, String toDate,
			@RequestParam(required = false) Character s) {
		ModelAndView mv = new ModelAndView(
				"/audit/forumRecord/forumRecordList.jsp");
		if (s != null)
			switch (s) {
			case '1':
				mv.addObject("msg", "保存成功！");
				break;
			case '2':
				mv.addObject("msg", "更新成功！");
				break;
			case '3':
				mv.addObject("msg", "删除成功！");
				break;
			case '4':
				mv.addObject("msg", "操作失败！");
				break;
			default:
				break;
			}
		mv.addObject("typelist", forumRecordService.query(fr));
		mv.addObject("type", "okd");
		mv.addObject("fromDate", fromDate);
		mv.addObject("toDate", toDate);
		mv.addObject("entity", fr);
		return mv;
	}

	/**
	 * 异步查询
	 * 
	 * @param fr
	 * @return
	 */
	@RequestMapping("/queryByPage")
	@ResponseBody
	public Map<String, Object> queryByPage(ForumRecord fr, String fromDate,
			String toDate) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 查询当天数据
		if ((fromDate == "" && toDate != "")
				|| (fromDate != "" && toDate == "")
				|| (fromDate == "" && toDate == "")) {
			long current = System.currentTimeMillis();// 当前时间毫秒数
			long zero = current / (1000 * 3600 * 24) * (1000 * 3600 * 24)
					- TimeZone.getDefault().getRawOffset();// 今天零点零分零秒的毫秒数
			Date date_b = new Timestamp(zero);
			long twelve = zero + 24 * 60 * 60 * 1000;// 今天24点0分0秒的毫秒数
			Date date_e = new Timestamp(twelve);
			SimpleDateFormat format = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			fromDate = format.format(date_b);
			toDate = format.format(date_e);
		}
		try {
			jsonMap.put("dataList",
					forumRecordService.query(fr, fromDate, toDate));
			jsonMap.put("iTotalDisplayRecords",
					forumRecordService.count(fr, fromDate, toDate));
			jsonMap.put("iTotalRecords", forumRecordService.count());
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return jsonMap;
	}

	/**
	 * 画图表，基于访问数在前limitMax的ip地址，tableType对应不同的图表，输入查询中的时间段
	 * 
	 * @param limitMax
	 *            int
	 * @param tableType
	 *            int
	 * @param fromD
	 * @param toD
	 * @return
	 */
	@RequestMapping("/showTable")
	@ResponseBody
	public Map<String, Object> showTable(int limitMax, int tableType,
			String fromD, String toD, long currentTime, long originalTime,
			int pos) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			if (tableType > 0) {
				// 2:记录中出现次数最多的ip num;1:forum types num;3:某时间段下的IPs逛论坛次数 ;
				// 4:针对3将时间轴整理成一小时为一个间隔
				List<String> ipsList = forumRecordService.queryTopIPs(limitMax);
				jsonMap.put("ctgr", ipsList);
				if (tableType == 2) {
					jsonMap.put("sr_data",
							forumRecordService.queryTopIPsNum(limitMax));
				} else if (tableType == 1) {
					List<List<Integer>> rsTypes = new ArrayList<List<Integer>>();
					List<List<Integer>> rsTypesNum = new ArrayList<List<Integer>>();
					List<Integer> tempListTypes = new ArrayList<Integer>();
					for (int i = 0; i < ipsList.size(); i++) {
						tempListTypes = forumRecordService
								.queryTopForumtypesByTopIp(ipsList.get(i),
										limitMax);
						rsTypes.add(i, tempListTypes);
						rsTypesNum.add(i, forumRecordService
								.queryTopForumtypesByTopIpNum(ipsList.get(i),
										limitMax));
					}
					jsonMap.put("types", rsTypes);
					jsonMap.put("typesNum", rsTypesNum);
				} else if ((tableType == 3 || tableType == 4)
						&& (fromD != null && fromD != "")
						&& (toD != null && toD != "")) {
					List<List<Integer>> rsTimes = new ArrayList<List<Integer>>();
					List<List<Integer>> rsTimesNum = new ArrayList<List<Integer>>();
					List<Integer> rsCnt = new ArrayList<Integer>();
					for (int j = 0; j < ipsList.size(); j++) {
						List<Integer> temp = forumRecordService
								.queryTopIpsVisitNumFromTo(ipsList.get(j),
										fromD, toD);
						rsCnt.add(j, temp.size());
						rsTimes.add(j, temp);
						rsTimesNum.add(j, forumRecordService
								.queryTopIpsVisitNumFromToNum(ipsList.get(j),
										fromD, toD));
					}
					jsonMap.put("addTimes", rsTimes);
					jsonMap.put("addTimesNum", rsTimesNum);
					if (tableType == 4) {
						jsonMap.put("cntAddTimes", rsCnt);
					}
				} else if (tableType == 5 && originalTime != 0
						&& currentTime != 0 && pos != 0) {
					List<Integer> rsCurrentCnt = new ArrayList<Integer>();
					// 刷新时间为1 second
					// alright 数据库查询当前时间段的数据为空时，在service中将其值设置为1
					Integer tempVisitNum = forumRecordService
							.queryTopIpsVisitNum(ipsList.get((pos - 1)),
									originalTime, currentTime).get(0);
					if (tempVisitNum == null) {
						tempVisitNum = 0;
					}
					jsonMap.put("currentRSNum", tempVisitNum);
				}
			}
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return jsonMap;
	}

	/**
	 * 展示列表头部访问总数图表展示
	 * @param user_ip
	 * @param user_account
	 * @param forum_title
	 * @param fromD
	 * @param toD
	 * @return
	 */
	@RequestMapping("/showTableHeader")
	@ResponseBody
	public Map<String, Object> showTableH(String user_ip, String user_account, String forum_title,
			String fromD, String toD) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		DateUtil du=new DateUtil();
		int minutes=du.getAverageTime(fromD,toD,6);
		try {
				jsonMap.put("dataList1",forumRecordService.queryTotals(user_ip,user_account,forum_title,fromD,toD,minutes,1));
				jsonMap.put("dataList2",forumRecordService.queryTotals(user_ip,user_account,forum_title,fromD,toD,minutes,2));
				jsonMap.put("dataList3",forumRecordService.queryTotals(user_ip,user_account,forum_title,fromD,toD,minutes,3));
				jsonMap.put("dataList4",forumRecordService.queryTotals(user_ip,user_account,forum_title,fromD,toD,minutes,4));
				jsonMap.put("dataList5",forumRecordService.queryTotals(user_ip,user_account,forum_title,fromD,toD,minutes,5));
				jsonMap.put("dataList6",forumRecordService.queryTotals(user_ip,user_account,forum_title,fromD,toD,minutes,6));
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "图形数据查询异常", e);
		}
		return jsonMap;
	}

	/**
	 * 下载查询的列表
	 * 
	 * @param fr
	 * @param fromDate
	 * @param toDate
	 * @param response
	 */
	@RequestMapping("/downExcel")
	public void downExcel(ForumRecord fr, String fromDate, String toDate,
			HttpServletResponse response) {
		if ((fromDate == "" && toDate != "")
				|| (fromDate != "" && toDate == "")
				|| (fromDate == "" && toDate == "")) {
			long current = System.currentTimeMillis();// 当前时间毫秒数
			long zero = current / (1000 * 3600 * 24) * (1000 * 3600 * 24)
					- TimeZone.getDefault().getRawOffset();// 今天零点零分零秒的毫秒数
			Date date_b = new Timestamp(zero);
			long twelve = zero + 24 * 60 * 60 * 1000;// 今天24点0分0秒的毫秒数
			Date date_e = new Timestamp(twelve);
			SimpleDateFormat format = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			fromDate = format.format(date_b);
			toDate = format.format(date_e);
		}
		List<ForumRecord> list = forumRecordService.query(fr, fromDate, toDate);

		// for(ForumRecord o : list) {
		// String s;
		// switch(o.getState()) {
		// case 1: s = "上线"; break;
		// case 2: s = "离线"; break;
		// default: s = ""; break;
		// }
		// o.setState_name(s);
		// }
		String[] titles = new String[] { "ID", "IP", "论坛类型", "访问账户", "论坛简介",
				"论坛组", "访问名称", "论坛类型", "添加时间" };
		String[][] fieldNames = new String[][] { { "id" }, { "user_ip" },
				{ "forum_type" }, { "user_account" }, { "forum_refer" },
				{ "forum_group" }, { "forum_title" }, { "forum_content" },
				{ "add_time" } };
		super.downExcel(list, titles, fieldNames, "论坛查询信息", response);
	}
}
